package com.example.vaultmysql.controller;

import com.example.vaultmysql.dto.DatabaseConnectionTestResult;
import com.example.vaultmysql.entity.DatabaseConfig;
import com.example.vaultmysql.service.DatabaseConfigService;
import com.example.vaultmysql.service.DatabaseConnectionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 数据库控制器
 * 提供数据库配置和连接测试的API接口
 * 
 * @author System
 * @version 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/database")
@CrossOrigin(origins = "*")
public class DatabaseController {

    @Autowired
    private DatabaseConfigService databaseConfigService;

    @Autowired
    private DatabaseConnectionService databaseConnectionService;

    /**
     * 获取所有数据库配置
     */
    @GetMapping("/configs")
    public ResponseEntity<List<DatabaseConfig>> getAllConfigs() {
        try {
            List<DatabaseConfig> configs = databaseConfigService.getAllDatabaseConfigs();
            return ResponseEntity.ok(configs);
        } catch (Exception e) {
            log.error("获取数据库配置失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 分页获取数据库配置
     */
    @GetMapping("/configs/page")
    public ResponseEntity<Page<DatabaseConfig>> getConfigsPage(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sortBy,
            @RequestParam(defaultValue = "asc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<DatabaseConfig> configs = databaseConfigService.getDatabaseConfigs(pageable);
            return ResponseEntity.ok(configs);
        } catch (Exception e) {
            log.error("分页获取数据库配置失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 根据ID获取数据库配置
     */
    @GetMapping("/configs/{id}")
    public ResponseEntity<DatabaseConfig> getConfigById(@PathVariable Long id) {
        try {
            Optional<DatabaseConfig> config = databaseConfigService.getDatabaseConfigById(id);
            return config.map(ResponseEntity::ok)
                         .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            log.error("获取数据库配置失败: id={}", id, e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 根据名称获取数据库配置
     */
    @GetMapping("/configs/name/{name}")
    public ResponseEntity<DatabaseConfig> getConfigByName(@PathVariable String name) {
        try {
            Optional<DatabaseConfig> config = databaseConfigService.getDatabaseConfigByName(name);
            return config.map(ResponseEntity::ok)
                         .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            log.error("获取数据库配置失败: name={}", name, e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取启用的数据库配置
     */
    @GetMapping("/configs/enabled")
    public ResponseEntity<List<DatabaseConfig>> getEnabledConfigs() {
        try {
            List<DatabaseConfig> configs = databaseConfigService.getEnabledDatabaseConfigs();
            return ResponseEntity.ok(configs);
        } catch (Exception e) {
            log.error("获取启用的数据库配置失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 搜索数据库配置
     */
    @GetMapping("/configs/search")
    public ResponseEntity<List<DatabaseConfig>> searchConfigs(@RequestParam String keyword) {
        try {
            List<DatabaseConfig> configs = databaseConfigService.searchDatabaseConfigs(keyword);
            return ResponseEntity.ok(configs);
        } catch (Exception e) {
            log.error("搜索数据库配置失败: keyword={}", keyword, e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 创建数据库配置
     */
    @PostMapping("/configs")
    public ResponseEntity<DatabaseConfig> createConfig(@RequestBody DatabaseConfig config) {
        try {
            DatabaseConfig savedConfig = databaseConfigService.createDatabaseConfig(config);
            return ResponseEntity.ok(savedConfig);
        } catch (Exception e) {
            log.error("创建数据库配置失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 更新数据库配置
     */
    @PutMapping("/configs/{id}")
    public ResponseEntity<DatabaseConfig> updateConfig(
            @PathVariable Long id, 
            @RequestBody DatabaseConfig config) {
        try {
            DatabaseConfig updatedConfig = databaseConfigService.updateDatabaseConfig(id, config);
            return ResponseEntity.ok(updatedConfig);
        } catch (Exception e) {
            log.error("更新数据库配置失败: id={}", id, e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 删除数据库配置
     */
    @DeleteMapping("/configs/{id}")
    public ResponseEntity<Map<String, Object>> deleteConfig(@PathVariable Long id) {
        try {
            databaseConfigService.deleteDatabaseConfig(id);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "数据库配置删除成功"
            ));
        } catch (Exception e) {
            log.error("删除数据库配置失败: id={}", id, e);
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "删除失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 启用/禁用数据库配置
     */
    @PatchMapping("/configs/{id}/toggle")
    public ResponseEntity<DatabaseConfig> toggleConfig(
            @PathVariable Long id, 
            @RequestParam boolean enabled) {
        try {
            DatabaseConfig config = databaseConfigService.toggleDatabaseConfig(id, enabled);
            return ResponseEntity.ok(config);
        } catch (Exception e) {
            log.error("切换数据库配置状态失败: id={}, enabled={}", id, enabled, e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 测试数据库连接
     */
    @PostMapping("/test-connection/{name}")
    public ResponseEntity<DatabaseConnectionTestResult> testConnection(@PathVariable String name) {
        try {
            DatabaseConnectionTestResult result = databaseConnectionService.testConnection(name);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("数据库连接测试失败: name={}", name, e);
            DatabaseConnectionTestResult result = DatabaseConnectionTestResult.failure(
                name, "连接测试失败: " + e.getMessage(), 0, "TEST_ERROR"
            );
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 测试数据库连接（不使用Vault）
     */
    @PostMapping("/test-connection/{name}/no-vault")
    public ResponseEntity<DatabaseConnectionTestResult> testConnectionNoVault(@PathVariable String name) {
        try {
            DatabaseConnectionTestResult result = databaseConnectionService.testConnection(name, false);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("数据库连接测试失败（无Vault）: name={}", name, e);
            DatabaseConnectionTestResult result = DatabaseConnectionTestResult.failure(
                name, "连接测试失败: " + e.getMessage(), 0, "TEST_ERROR"
            );
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 批量测试数据库连接
     */
    @PostMapping("/test-connections")
    public ResponseEntity<Map<String, DatabaseConnectionTestResult>> testConnections(
            @RequestBody List<String> databaseNames) {
        try {
            Map<String, DatabaseConnectionTestResult> results = Map.of();
            
            for (String name : databaseNames) {
                try {
                    DatabaseConnectionTestResult result = databaseConnectionService.testConnection(name);
                    results.put(name, result);
                } catch (Exception e) {
                    DatabaseConnectionTestResult result = DatabaseConnectionTestResult.failure(
                        name, "连接测试失败: " + e.getMessage(), 0, "TEST_ERROR"
                    );
                    results.put(name, result);
                }
            }
            
            return ResponseEntity.ok(results);
        } catch (Exception e) {
            log.error("批量测试数据库连接失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取连接池状态
     */
    @GetMapping("/connection-pool/{name}/status")
    public ResponseEntity<Map<String, Object>> getConnectionPoolStatus(@PathVariable String name) {
        try {
            Map<String, Object> status = databaseConnectionService.getConnectionPoolStatus(name);
            return ResponseEntity.ok(status);
        } catch (Exception e) {
            log.error("获取连接池状态失败: name={}", name, e);
            return ResponseEntity.badRequest().body(Map.of(
                "exists", false,
                "error", e.getMessage()
            ));
        }
    }

    /**
     * 刷新连接池
     */
    @PostMapping("/connection-pool/{name}/refresh")
    public ResponseEntity<Map<String, Object>> refreshConnectionPool(@PathVariable String name) {
        try {
            databaseConnectionService.refreshDataSource(name);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "连接池刷新成功"
            ));
        } catch (Exception e) {
            log.error("刷新连接池失败: name={}", name, e);
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "刷新失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取数据库配置统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<DatabaseConfigService.DatabaseConfigStats> getStats() {
        try {
            DatabaseConfigService.DatabaseConfigStats stats = databaseConfigService.getStats();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("获取数据库配置统计信息失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 批量创建数据库配置
     */
    @PostMapping("/configs/batch")
    public ResponseEntity<List<DatabaseConfig>> createConfigs(@RequestBody List<DatabaseConfig> configs) {
        try {
            List<DatabaseConfig> savedConfigs = databaseConfigService.createDatabaseConfigs(configs);
            return ResponseEntity.ok(savedConfigs);
        } catch (Exception e) {
            log.error("批量创建数据库配置失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
}